package cn.itcast.bos.action;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.FixedAreaService;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@ParentPackage(value = "json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class FixedAreaAction extends BaseAction<FixedArea> {

	private static final long serialVersionUID = 1L;

	@Autowired
	private FixedAreaService fixedAreaService;

	/**
	 * 保存客户
	 */
	@Action(value = "fixedArea_save", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/fixed_area.html") })
	public String save() {
		fixedAreaService.save(model);
		return SUCCESS;
	}

	/**
	 * 查询没有被关联的客户
	 */
	@Action(value = "fixedArea_findNoAssociationCustomers", results = { @Result(name = "success", type = "json") })
	public String findNoAssociationCustomers() {
		// 使用webClient调用 webService接口
		Collection<? extends Customer> collection = WebClient
				.create("http://localhost:9002/crm_management/services/customerService/findNoAssociationCustomers")
				.accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
		ActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}

	/**
	 * 根据定区查询被关联的客户:单击事件
	 */
	private String fixedAreaId;
	public void setFixedAreaId(String fixedAreaId) {
		this.fixedAreaId = fixedAreaId;
	}
	@Action(value = "customer_findAssociation", results = {
			@Result(name = "success", type = "json") })
	public String findAssociation() {
		// 使用webClient调用 webService接口
		Collection<? extends Customer> collection = WebClient
				.create("http://localhost:9002/crm_management/services/customerService/customer_findAssociation/"
						+ fixedAreaId)
				.accept(MediaType.APPLICATION_JSON)// 有返回值用accept
				.type(MediaType.APPLICATION_JSON)// 有参数用type
				.getCollection(Customer.class);//指定查询哪个对象
		ActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}

	/**
	 * 根据定区查询被关联的客户:单击事件
	 */
	@Action(value = "fixedArea_findHasAssociationFixedAreaCustomers", results = {
			@Result(name = "success", type = "json") })
	public String findHasAssociationFixedAreaCustomers() {
		// 使用webClient调用 webService接口
		Collection<? extends Customer> collection = WebClient
				.create("http://localhost:9002/crm_management/services/customerService/findHasAssociationFixedAreaCustomers/"
						+ model.getId())
				.accept(MediaType.APPLICATION_JSON)// 有返回值用accept
				.type(MediaType.APPLICATION_JSON)// 有参数用type
				.getCollection(Customer.class);
		ActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}

	// 属性驱动
	private String[] customerIds;

	public void setCustomerIds(String[] customerIds) {
		this.customerIds = customerIds;
	}

	/**
	 * 定区关联客户
	 */
	@Action(value = "fixedArea_associationCustomersToFixedArea", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/fixed_area.html") })
	public String associationCustomersToFixedArea() {
		// 将数组转换成用逗号隔开的字符串
		String customerIdStr = StringUtils.join(customerIds, ",");
		// 使用webClient调用 webService接口
		WebClient
				.create("http://localhost:9002/crm_management/services/customerService/associationCustomersToFixedArea?customerIdStr="
						+ customerIdStr + "&fixedAreaId=" + model.getId())
				// 注意：因为对面需要使用@QueryParam接收2个参数，所有这里不能使用path()指定路径，否则?号出现乱码
				.put(null);
		return SUCCESS;
	}

	/**
	 * 定区关联快递员
	 */

	// 获取快递员ID与收派时间id
	private String courierId;
	private String takeTimeId;

	public void setCourierId(String courierId) {
		this.courierId = courierId;
	}

	public void setTakeTimeId(String takeTimeId) {
		this.takeTimeId = takeTimeId;
	}

	@Action(value = "fixedArea_associationCourierToFixedArea", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/fixed_area.html") })
	public String associationCourierToFixedArea() {
		fixedAreaService.associationCourierToFixedArea(model.getId(), courierId, takeTimeId);
		return SUCCESS;
	}

	/**
	 * 有条件分页查询
	 */

	private int page;
	private int rows;

	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	@Action(value = "fixed_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		Pageable pageable = new PageRequest(page - 1, rows);
		/** 带条件的查询 */
		Specification<FixedArea> specification = new Specification<FixedArea>() {

			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// Root 用于获取属性字段，CriteriaQuery可以用于简单条件查询，CriteriaBuilder
				// 用于构造复杂条件查询（多表）
				Predicate predicate = null;
				List<Predicate> list = new ArrayList<Predicate>();
				if (StringUtils.isNoneBlank(model.getId())) {
					Predicate p = cb.equal(root.get("id").as(String.class), model.getId());
					list.add(p);
				}
				if (StringUtils.isNoneBlank(model.getCompany())) {
					Predicate p = cb.like(root.get("company").as(String.class), "%" + model.getCompany() + "%");
					list.add(p);
				}

				if (list != null && list.size() > 0) {
					Predicate[] p = new Predicate[list.size()];
					predicate = cb.and(list.toArray(p));
				}
				return predicate;
			}
		};
		// 带有条件的查询
		Page<FixedArea> pagedata = fixedAreaService.findPageDate(specification, pageable);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", pagedata.getTotalElements());
		map.put("rows", pagedata.getContent());

		ServletActionContext.getContext().getValueStack().push(map);

		return SUCCESS;
	}

}
